<?php
/**
 * login.php
 * 
 * The file contains the code for the user login webpage.
 */
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];

require_once 'interface.php';
webpageDoctype();
print_html_title("Member System - Login");
webpageMetaAndBodyStart();
echo "<p><div align='center'>";
echo "<h2>Login</h2><br/>";
	
	if(strlen($username) > 0 && strlen($userid) > 0) {
		echo "You are already logged in as <b>$username</b>. <a href='./member.php'>Click here</a> to go to the members page.";
	}else{
	
	$form = "<form action ='./login.php' method='post'>
			<table>
			<tr>
            	<td>Username:</td>
            	<td><input type='text' name='user' /></td>
			</tr>
			<tr>
           		<td>Password:</td>
           		<td><input type='password' name='password' /></td>
			</tr>
			<tr>
				<td colspan='2' align='center'><input type='submit' name='loginbutton' value='login' /></td>	
			</tr>
			<tr>
				<td colspan='2' align='center'><a href='./register.php'>Register</a></td>
			</tr>
			<tr>
				<td colspan='2' align='center'><a href='./forgotpass.php'>Forgot your password?</a></td>	
			</tr>
			</table>
			</form>";
				
			if ($_POST['loginbutton'] === "login"){
				$user = $_POST['user'];
				$password = $_POST['password'];
				
				if (strlen($user) > 0) {
					if (strlen($password) > 0) {
						
						require("connect.php");
						
						//make sure login info correct
						
						$query = mysql_query("SELECT * FROM users WHERE username='$user'");
						$numrows = mysql_num_rows($query);
						if ($numrows == 1){
							$row = mysql_fetch_assoc($query);
							$dbid = $row['id'];
							$dbuser = $row['username'];
							$dbpass = $row['password'];
							$dbactive = $row['active'];
							
							if ($password === $dbpass) {
								if ($dbactive == 1){
									//set session info
									$_SESSION['userid'] = $dbid;
									$_SESSION['username'] = $dbuser;
									
									echo <<<EOL
									<meta http-equiv="Refresh" content="10; url=member.php" />
									<h3>
									You have been logged in as <b>$dbuser</b>.<br/>
									You will shortly be redirected to the members page.<br/><br/>
									<a href='./member.php'>Click here</a> to go to the members page.<br/><br/>
									</h3>
EOL;
								}else{
									echo "You must activate your account to login. $form";
								}
							}else{
								echo "You did not enter the correct password. $form";
							}
						}else{
							echo "The username you entered was not found. $form";
						}
						mysql_close($con);
						
					} else{
						echo "You must enter your password. $form";
					}
				}else {
					echo "You must enter your username. $form";
				}
			}else{
				echo $form;
			}
	}
echo "</div></p>";
webpageFooter();
?>
